package Jun13.doc;

import Jun13.pojo.User;
import Jun13.utils.ESUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class InsertBatchDoc {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient rest = ESUtils.getRest();//获取ES对象
        BulkRequest bulk = new BulkRequest();//创建批量对象
        ObjectMapper om = new ObjectMapper();//创建ObjectMapper
        String r = null;//创建空字符串，后续直接做字符串赋值
        for (int i=0;i<10;i++){//循环十次
            User u = new User("user" + i, i, i%3==0?"男":"女");//每次产生一个对象
            r = om.writeValueAsString(u);//写成json字符串
            bulk.add(new IndexRequest().index("user").id(String.format("100%d", i)).source(r,XContentType.JSON));//添加进bulk中
        }
        BulkResponse result = rest.bulk(bulk, RequestOptions.DEFAULT);//将批量加入的数据发送
        System.out.println(result.status());//打印结果
        rest.close();//关闭
    }
}
